package roots;

import java.io.*;
//import java.math.*;

/**
 * 	@author Coenie
 *	Feb 18, 2009
 * 	roots
 */
public class Main {

	/**
	 * @param Args
	 * @throws IOException
	 */
	public static void main(String[] Args) throws IOException {
		
		final double a = Math.pow(2, 60);  //bepaal wortel van
		final double n = 2000000.0;  //bepaal soveelste wortel
		double aRoot = a/n; //die wortel
		//double regteWortel = Math.pow(a, 1/n);
		int i = 0;
		final double acc = 0.000000000000000001;
		//int c = 0;
		double diff = 0;
		
		//BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		
		//System.out.println("0) newton x 5\n1) fast newton \n2) normal newton");
		
		//c = Integer.parseInt(in.readLine());
		
		long einde = 0;
		long time = 0;
		
		//Apparently fast converging newton's method
		long begin = System.currentTimeMillis();
		while(true){
			
			diff = Math.abs(aRoot - diff);
			
			if(diff < acc){
				
				einde = System.currentTimeMillis();
				time = einde - begin;
				System.out.println("Fast converging newton:\nRoot: "+ aRoot +"\nIterations: "+i+"\nTime: "+ time);
				break;
			}
			
			diff = aRoot;
			aRoot = (1.0/(n))*((n - 1.0)*aRoot +(a)/(Math.pow(aRoot, n - 1.0)));
			
			i++;
		}
		
		
	/*
		//normal newton's method
		aRoot = a/n;
		i  = 0;
		begin = System.currentTimeMillis();
		while(true){
			
			diff = Math.abs(aRoot - diff);
			
			if(diff < acc){
				
				einde = System.currentTimeMillis();
				time = einde - begin;
				System.out.println("Newtons method:\nRoot: "+ aRoot +"\nIterations: "+i+"\nTime: "+ time);
				break;
			}
			diff = aRoot;
			aRoot = aRoot - (Math.pow(aRoot, n) - a)/(n*(Math.pow(aRoot, n - 1.0)));
			
			i++;
		}
		
		*/
		//newton's method x 5
		aRoot = a/n;
		i  = 0;
		begin = System.currentTimeMillis();
		while(true){
			
			diff = Math.abs(aRoot - diff);
			
			if(diff < acc){
				
				einde = System.currentTimeMillis();
				time = einde - begin;
				System.out.println("Newton x5:\nRoot: "+ aRoot +"\nIterations: "+i+"\nTime: "+ time);
				break;
			}
			double x1 = aRoot, x2 = 0, x3 = 0, x4 = 0;
			
			x2 = x1 - x1/n + a/(n*(Math.pow(x1, n - 1)));
			x3 = x2 - x2/n + a/(n*(Math.pow(x2, n - 1)));
			x4 = x3 - x3/n + a/(n*(Math.pow(x3, n - 1)));
			aRoot = x4 - x4/n + a/(n*(Math.pow(x4, n - 1)));
			diff = x4;
			
			i++;
		}
		
		
		
		//in.read();
		
	}
	
	
	
	
}
